const {article} = require('../../utils/config')
const {getDetail, queryCollect} = require('../../utils/request')
const {addCollect, removeCollect} = require('../../utils/cloudRequest')
Page({

    data: {
        id: '',
        detail: {},
        collect: '收藏',
        loading: false
    },
    onCollect() {
        //未登录
        if (!wx.getStorageSync('logged')) {
            wx.showModal({
                content: '请登录后进行操作',
                cancelText: '取消',
                confirmText: '登录',
                cancelColor: 'red',
                confirmColor: '#ffffff',
                success: res => {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '../login/index'
                        })
                    }
                }
            })
            return
        }
        const openid = wx.getStorageSync('openid');
        queryCollect('article', openid, this.data.id).then(res => {
            //未收藏过，进行收藏
            if (res.data.length === 0) {
                addCollect('article', openid, this.data.detail, this.data.id).then(res => {
                    this.setData({
                        collect: '已收藏'
                    })
                })
            } else {
                //已收藏，取消收藏
                removeCollect('article', openid, this.data.id).then(res => {
                    this.setData({
                        collect: '收藏'
                    })
                })
            }
        })
    },

    onLoad(event) {
        const {
            id
        } = event
        this.setData({
            id
        })
        queryCollect('article', wx.getStorageSync('openid'), id).then(res => {
            if (res.data.length !== 0) {
                this.setData({
                    collect: '已收藏'
                })
            }
        })
        getDetail(article, id).then(res => {
            this.setData({
                detail: res.data
            })
            //为了更好的渲染，缓冲
            setTimeout(() => {
                this.setData({
                    loading: true
                })
            }, 1000)
        })
    },
    onShareAppMessage(e) {
        return {
            title: this.data.detail.title,
            imageUrl: this.data.detail.img,
            path: `pages/articleDetail/index?id=${this.data.id}`
        }

    },
})